
SUDO        ?=
RB_USER     ?= rb
RB_USERDIR  ?= /var/home/${RB_USER}
TMPSUDOERS  != mktemp /usr/local/etc/sudoers.rb.XXXXXXXXXX
TMPSUDOERS2 != mktemp /usr/local/etc/sudoers.rb.XXXXXXXXXX

# TMPSUDOERS* are not removed on error in anything except install-sudo,
# so we need to care about this ourself.

all: install

install: install-user install-sudo install-flags

update: remove-user install

install-user:
	@echo "===> Creating system user ${RB_USER}"
	(/usr/sbin/pw useradd ${RB_USER} -d ${RB_USERDIR} -m -s /bin/sh -L daemon -G '' && \
	    /usr/sbin/pw lock ${RB_USER} && \
	    chmod 0700 ${RB_USERDIR} && \
	    install -d -o ${RB_USER} -m 0700 ${RB_USERDIR}/.ssh && \
	    install -o ${RB_USER} -m 0400 authorized_keys ${RB_USERDIR}/.ssh/ && \
	    install -o ${RB_USER} -m 0400 my.cnf ${RB_USERDIR}/.my.cnf) \
	    || (rm -f ${TMPSUDOERS} ${TMPSUDOERS2}; false)

remove-user:
	@echo "===> Removing system user ${RB_USER}"
	-/usr/sbin/pw userdel ${RB_USER} -r

install-sudo:
	@echo "===> Adding record for user ${RB_USER} in sudoers(5)"
	cp -p /usr/local/etc/sudoers ${TMPSUDOERS}
# Required by sudo(8)
	chown root:wheel ${TMPSUDOERS2}
	(	(sed -e '/^[[:space:]]*${RB_USER}[[:space:]]/d' < ${TMPSUDOERS} && \
		printf "\n%-15s ALL=(root) NOPASSWD: ${RB_USERDIR}/rb_agent verbose filter *" "${RB_USER}" && \
		printf "\n%-15s ALL=(root) NOPASSWD: ${RB_USERDIR}/rb_agent filter *" "${RB_USER}" && \
		printf "\n%-15s ALL=(root) NOPASSWD: /bin/pax -w -x cpio -- *" "${RB_USER}" && \
		printf "\n%-15s ALL=(root) NOPASSWD: /bin/pax -w -x cpio -d" "${RB_USER}" && \
		printf "\n%-15s ALL=(root) NOPASSWD: /usr/bin/tee -- /home/*/*" "${RB_USER}" && \
		printf "\n%-15s ALL=(root) NOPASSWD: /usr/bin/chgrp * /home/*/*" "${RB_USER}" && \
		printf "\n%-15s ALL=(CLIENTS) NOPASSWD: /bin/pax -r -- *\n" "${RB_USER}" \
		) >${TMPSUDOERS2} && \
		install -o root -g wheel -m 0440 ${TMPSUDOERS2} /usr/local/etc/sudoers && \
		${SUDO} su ${RB_USER} -c "sudo -l </dev/null") || \
	(echo "Failed lines: "; tail -2 /usr/local/etc/sudoers; \
		mv ${TMPSUDOERS} /usr/local/etc/sudoers; rm -f ${TMPSUDOERS2}; false)
	rm ${TMPSUDOERS} ${TMPSUDOERS2}

install-flags:
	@echo "===> Setting nodump flag for directories to be dumped"
	chflags nodump /home /var/db/mysql || \
	(rm -f ${TMPSUDOERS} ${TMPSUDOERS2}; false)

# Try to play safe
.END:
	@echo "===> Removing temporary file"
	rm -f ${TMPSUDOERS} ${TMPSUDOERS2}

.INTERRUPT:
	@echo "===> Removing temporary file"
	rm -f ${TMPSUDOERS} ${TMPSUDOERS2}

